package com.cskaoyan.order.mq.consumer;

import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.service.OrderCoreService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.*;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @author: 杨庆
 * @since: 2022.9.23 17:21
 * @description:
 */
@Component
@Slf4j
public class DelayOrderCannelConsumer {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderCoreService orderCoreService;

    private DefaultMQPushConsumer consumer;
    @PostConstruct
    public void init() {
        consumer = new DefaultMQPushConsumer("delay_order_consumer");
        consumer.setNamesrvAddr("127.0.0.1:9876");

        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                //TODO 订单的处理逻辑
                MessageExt messageExt = list.get(0);
                byte[] body = messageExt.getBody();
                try {
                    String orderId = new String(body, 0, body.length, "utf-8");
                    //查询订单的状态
                    Order order = orderMapper.selectByPrimaryKey(orderId);
                    if (order != null) {

                        if (order.getStatus() == 0) {
                            //TODO 没有付款的,就直接取消订单即可
                            orderCoreService.cancelOrder(orderId);
                        }
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        try {
            consumer.subscribe("delay_order","*");
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }

    }

}
